package sma.interf;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Constat & utility for RMI binding.
 * 
 * @author smarsoll
 * 
 */
public class BindUtil {

	private final static Logger LOGGER = LoggerFactory.getLogger(BindUtil.class);

	public static final String REGISTRY_HOST = "D4244";

	public static final String BASE_NAME = "CalculateIss-";

	public static final int NB_MAX_BIND = 30;

	public static String HOST_NAME = "default";

	static {
		InetAddress addr;
		try {
			addr = InetAddress.getLocalHost();
			HOST_NAME = new String(addr.getHostName());
		} catch (UnknownHostException e) {
			LOGGER.error("", e);
		}

	}

	public static final String getBindName(int num) {
		return BASE_NAME + num;
	}

	/**
	 * get a free name not already bound.
	 * 
	 * @param alreadybound
	 * @return null if non found
	 */
	public static String getFreeBindName(String[] alreadybound) {
		Collection<String> alreadyB = Arrays.asList(alreadybound);
		for (int i = 0; i < NB_MAX_BIND; i++) {
			String nameToTest = getBindName(i);
			if (!alreadyB.contains(nameToTest)) {
				return nameToTest;
			}

		}
		LOGGER.warn("No free name found!");
		return null;
	}

}
